package com.iflytek.demo.ability.ots;

import com.iflytek.demo.ability.Tools;
import ohos.utils.zson.ZSONObject;
import okhttp3.*;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 讯飞开放平台 翻译
 * https://www.xfyun.cn/doc/nlp/niutrans/API.html
 *
 * @author zhhuang10
 * @date 2021/7/2
 */
public class OtsClient {

    // 服务端地址 
    private final String mHostUrl = "https://ntrans.xfyun.cn/v2/ots";
    private final String mHost = "ntrans.xfyun.cn";
    private final String mPath = "/v2/ots";

    // 账号参数
    private String mAppId;
    private String mApiSecret;
    private String mApiKey;

    // 源语言
    private String mFromLang = "cn";
    // 翻译成
    private String mToLang = "en";
    // 需要翻译的文本
    private String otsText = "你好";
    // okhttp call
    private Call mCall;

    public void setAppId(String appId) {
        this.mAppId = appId;
    }

    public void setApiSecret(String apiSecret) {
        this.mApiSecret = apiSecret;
    }

    public void setApiKey(String apiKey) {
        this.mApiKey = apiKey;
    }

    /**
     * 开始翻译
     *
     * @param text     需要翻译的文本
     * @param fromLang 源语种
     * @param toLang   目标语种
     * @return 翻译结果
     */
    public final String start(String text, String fromLang, String toLang) {
        this.otsText = text;
        this.mFromLang = fromLang;
        this.mToLang = toLang;
        String body = buildHttpBody();
        HashMap<String, String> header = buildHttpHeader(body);
        try {
            return post(this.mHostUrl, header, body);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * post请求
     */
    private String post(String url, Map<String, String> headerMap, String str) throws Exception {
        OkHttpClient client = Tools.okHttp();
        MediaType mediaType = MediaType.get("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(mediaType, str);
        Request.Builder builder = (new Request.Builder()).url(url).post(body);
        for (String s : headerMap.keySet()) {
            builder.header(s, headerMap.get(s));
        }
        Request request = builder.build();
        this.mCall = client.newCall(request);
        Response response = mCall.execute();
        if (response.isSuccessful() && response.body() != null) {
            OtxBean otxBean = ZSONObject.stringToClass(response.body().string(), OtxBean.class);
            if (otxBean.code != 0) {
                return null;
            }
            return otxBean.data.result.trans_result.dst;
        }
        return null;
    }

    /**
     * 取消
     */
    public final void cancel() {
        if (mCall != null) {
            mCall.cancel();
        }
    }

    /**
     * 生成http请求头
     */
    public final HashMap<String, String> buildHttpHeader(String body) {
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        String date = format.format(new Date());
        String digestBase64 = this.getDigest(body);
        LinkedHashMap<String, String> header = new LinkedHashMap<>();
        header.put("Content-Type", "application/json");
        header.put("Accept", "application/json,version=1.0");
        header.put("Host", this.mHost);
        header.put("Date", date);
        header.put("Digest", digestBase64);
        header.put("Authorization", this.getAuthStr(date, digestBase64));
        return header;
    }

    /**
     * 请求 Body
     */
    private String buildHttpBody() {
        ZSONObject zsonObject = new ZSONObject();
        {
            ZSONObject common = new ZSONObject();
            common.put("app_id", mAppId);
            zsonObject.put("common", common);
        }
        {
            ZSONObject business = new ZSONObject();
            business.put("from", mFromLang);
            business.put("to", mToLang);
            zsonObject.put("business", business);
        }
        {
            ZSONObject data = new ZSONObject();
            data.put("text", Tools.base64(otsText));
            zsonObject.put("data", data);
        }
        return zsonObject.toString();
    }

    /**
     * 请求头的摘要
     */
    private String getDigest(String body) {
        return "SHA-256=" + Tools.base64(Tools.sha256(body.getBytes()));
    }

    /**
     * 鉴权
     */
    private String getAuthStr(String date, String digest) {
        String str = "host: " + this.mHost
                + "\ndate: " + date
                + "\nPOST " + this.mPath + " HTTP/1.1"
                + "\ndigest: " + digest;
        String signature = Tools.base64(Tools.hmacsha256(str.getBytes(), mApiSecret.getBytes()));
        return "api_key=\"" + this.mApiKey + "\", algorithm=\"hmac-sha256\", headers=\"host date request-line digest\", signature=\"" + signature + '"';

    }

    /**
     * 结果解析类
     */
    public static class OtxBean {
        public int code;
        public Data data;
        public String message;
        public String sid;
    }

    public static class Data {
        public Result result;
    }

    public static class Result {
        public String from;
        public String to;
        public TransResult trans_result;
    }

    public static class TransResult {
        public String dst;
        public String src;
    }
}
